/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.server.handler;

import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.server.common.RuntimeEnv;
import cn.ac.iie.di.wx.server.httpservice.HttpSender;
import cn.ac.iie.di.wx.server.utils.RedisUtil;
import cn.ac.iie.di.wx.server.utils.TimeStampUtil;
import cn.ac.iie.di.wx.server.vo.OracleUpdateVo;
import cn.ac.iie.di.wx.server.vo.RedisVo;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class OCR_ThemesHandler implements HandlerI {

    static Logger logger = Logger.getLogger(OCR_ThemesHandler.class.getName());

    @Override
    public void init() throws Exception {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String overSeaAccountQuery = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
        logger.info("receive OCR request:" + overSeaAccountQuery);
        //解析请求，获取请求业务编号id,若请求得到成功响应，则到指定文件夹下获取相应的json文件，从该文件获取布控的结果
        try {
            JSONObject addGroupMonitorJson = JSONObject.parseObject(overSeaAccountQuery);
            String opid = addGroupMonitorJson.getString("opid");//存redis里，将关键字存value里面
            String param = addGroupMonitorJson.getString("param");
            //将系统参数补全
            addGroupMonitorJson.put("areaid", (String) RuntimeEnv.getParam(RuntimeEnv.areaid));
            addGroupMonitorJson.put("userareaid", (String) RuntimeEnv.getParam(RuntimeEnv.userareaid));
            addGroupMonitorJson.put("sysid", (String) RuntimeEnv.getParam(RuntimeEnv.sysid));
            addGroupMonitorJson.put("sysuserid", (String) RuntimeEnv.getParam(RuntimeEnv.sysuserid));
            logger.info(addGroupMonitorJson.toJSONString());
            //主题为1
            String responseStr = "";//若frontnum=0，则表示请求已经处理完成

            RuntimeEnv.redisVos.put(new RedisVo(opid, "1"));
            logger.info("put into redisqueue " + opid);
            //增加限制
            int count = 0;
            boolean responseCode = false;
            while (count <= 1000) {
                if (RuntimeEnv.OCRcommitLimit.get() < Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.OCRcommitMax))) {
                    logger.info("当前=" + RuntimeEnv.OCRcommitLimit + "最大限制=" + (String) RuntimeEnv.getParam(RuntimeEnv.OCRcommitMax));
                    RuntimeEnv.OCRcommitLimit.incrementAndGet();
                    long st = System.currentTimeMillis();
                    HttpSender hs = new HttpSender();
                    responseStr = hs.closableHttpClient(addGroupMonitorJson.toJSONString(), (String) RuntimeEnv.getParam(RuntimeEnv.OCRQuery));
//                    responseStr = "{\"opid\": " + opid + ",\"msgid\": \"123456\",\"frontnum\": 0,\"status\": \"200\"}";
                    //解析响应
                    long et = System.currentTimeMillis();
                    logger.info("发送烽火时长=" + (et - st) + " ms");
                    if (responseStr.equals("")) {
                        //失败情况
                        logger.info("OCR response is null");
                        responseStr = "{\"opid\": \"" + opid + "\",\"desc\": \"err烽火超时异常\",\"frontnum\": -1,\"status\": \"404\"}";;
                    } else {
                        logger.info("OCR response is sucess:" + responseStr);
                        try {
                            JSONObject jSONObject = JSONObject.parseObject(responseStr);
                            String frontnum = jSONObject.getString("frontnum");
                            String status = jSONObject.getString("status");
                            if (status.equals("200")) {
                                //状态正常
                                if (frontnum.equals("0")) {
                                    logger.info("OCR response is 200");
                                } else {
                                    logger.info("OCR该业务正在排队中");
                                }
                            } else {
                                logger.info("OCR业务请求状态不正常");
                                //如果是超限
                                if (status.equals("400")) {
                                    responseCode = true;
                                    logger.info("烽火返回400");
                                }
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }

                    break;
                }
                if (count >= 1000) {
                    logger.info("访问量超限");
                    String responseOutOFLimit = "{\"opid\": \"" + opid + "\",\"desc\": \"err烽火超时异常，服务器超限\",\"frontnum\": -1,\"status\": \"404\"}";
                    logger.info(responseOutOFLimit);
                    responseStr = responseOutOFLimit;
                    break;
                }
                ++count;
                Thread.sleep(100);
            }
            //给客户端发送响应消息
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            if (responseCode) {
                response.setStatus(211);
            }
            BufferedOutputStream bos = new BufferedOutputStream(out);
            InputStream inputStream = new ByteArrayInputStream(responseStr.getBytes("UTF-8"));
            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                bos.write(bytesContent, 0, bytesReadIn);
            }
            RuntimeEnv.OCRCount.getAndIncrement();
            bos.flush();
            bos.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            RuntimeEnv.OCRcommitLimit.decrementAndGet();
        }
    }

}
